package com.example.test.advice.第三章_类_对象_方法.建议34_构造函数尽量简化;

public class Client {

    public static void main(String[] args) {
        //Server s = new SimpleServer(1000);
        
        ServerUpdate su = new SimpleServerUpdate(1000);
    }
}

//定义一个服务
abstract class Server{

    public final static int DEFAULT_PORT = 40000;

    public Server() {
        //获得子类提供的端口号
        int port = getPort();
        System.out.println("端口号："+port);
        /*进行监听动作*/
    }

    //由子类提供端口号，并进行可行性检查
    protected abstract int getPort();
}

class SimpleServer extends Server{

    private int port = 100;

    //初始化传递一个端口


    public SimpleServer(int port) {
        this.port = port;
    }

    //检查端口是否有效，无效则使用默认端口，这里使用随机数模拟
    @Override
    protected int getPort() {
        double r = Math.random();
        System.out.println("r :"+r+",port:"+port);
        return r > 0.5 ? port:DEFAULT_PORT;
    }
}

abstract class ServerUpdate{

    public final static int DEFAULT_PORT = 40000;

    public ServerUpdate() {

    }

    public void start(){
        int port = getPort();
        System.out.println("升级版：port:"+port);
    }

    protected abstract int getPort();
}

class SimpleServerUpdate extends ServerUpdate{

    private int port = 100;

    public SimpleServerUpdate(int port) {
        this.port = port;
        start();
    }

    @Override
    protected int getPort() {
        double r = Math.random();
        System.out.println("升级版--r :"+r+",port:"+port);
        return r > 0.5 ? port:DEFAULT_PORT;
    }
}
